package com.iotteam.androidbase.commen;

import android.content.Context;
import android.content.SharedPreferences;

import com.iotteam.androidbase.base.BaseApplication;
import com.iotteam.androidbase.commen.utils.ObjectUtil;
import com.iotteam.androidbase.commen.utils.PLog;
import com.iotteam.androidbase.moudules.login.model.LoginInfo;

/**
 * 本地信息存取
 * Created by lidechen on 5/5/17.
 */

public class LocalInfoManager {

    private static final String SP_NAME_LOCAL_INFO = "sp_name_local_info";

    private static final String KEY_USER_INFO = "key_user_info";

    public static SharedPreferences sSp;
    private SharedPreferences.Editor mEdit;

    private static LocalInfoManager sInstance = new LocalInfoManager();
    private LocalInfoManager(){
        sSp = BaseApplication.getAppContext().getSharedPreferences(SP_NAME_LOCAL_INFO, Context.MODE_PRIVATE);
    }

    public static LocalInfoManager getInstance(){
        return sInstance;
    }

    private synchronized void write(String key, String data){
        mEdit = sSp.edit();
        mEdit.putString(key, data);
        mEdit.commit();
    }

    private synchronized String read(String key){
        return sSp.getString(key, null);
    }

    public void saveUserInfo(LoginInfo userInfo){
        String str = ObjectUtil.objectToBase64Code(userInfo);
        write(KEY_USER_INFO, str);
    }

    public LoginInfo getUserInfo(){
        LoginInfo userInfo;
        String str = read(KEY_USER_INFO);
        if(str != null) {
            userInfo = ObjectUtil.base64codeToObject(str);
        }else {
            return null;
        }
        return userInfo;
    }

    public boolean isLogin(){
        if(getUserInfo() != null){
            return true;
        }else {
            return false;
        }
    }
}
